package com.niuwa.p2p.core.pdf.factory;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.LinkedHashMap;

import org.xhtmlrenderer.pdf.ITextFSImage;
import org.xhtmlrenderer.pdf.ITextOutputDevice;
import org.xhtmlrenderer.pdf.ITextUserAgent;
import org.xhtmlrenderer.resource.CSSResource;
import org.xhtmlrenderer.resource.ImageResource;
import org.xhtmlrenderer.util.XRLog;

import com.itextpdf.text.Image;

  
/** 
 * 修改xhtmlrenderer获取css和image资源的方式为网络 
 * HttpURLUserAgent
 * @Description: 修改xhtmlrenderer获取css和image资源的方式为网络
 * @author jsj
 */  
public class HttpURLUserAgent extends ITextUserAgent {  
    /** 
     * an LRU cache 
     */
    private int imageCacheCapacity = 16; 
    private LinkedHashMap<String, ImageResource> imageCache =  
            new LinkedHashMap<String, ImageResource>(imageCacheCapacity, 0.75f, true) {  
                private static final long serialVersionUID = -2333998499957890105L;  
  
                protected boolean removeEldestEntry(java.util.Map.Entry<String, ImageResource> eldest) {  
                    return size() > imageCacheCapacity;  
                }  
            };  
  
    public HttpURLUserAgent(ITextOutputDevice outputDevice) {  
        super(outputDevice);  
    }  
      
    /** 
     * 从网络取得CSS资源
     * @param uri 
     */
    @Override  
    public CSSResource getCSSResource(String uri) {  
        InputStream is = null;  
        uri = resolveURI(uri);  
        try {  
            URLConnection uc = new URL(uri).openConnection();  
            uc.connect();  
            is = uc.getInputStream();  
        } catch (MalformedURLException e) {  
            XRLog.exception("bad URL given: " + uri, e);  
        } catch (IOException e) {  
            XRLog.exception("IO problem for " + uri, e);  
        }  
        return new CSSResource(is);  
    }  
  
    /** 
     * 从网络取得Image资源
     * Document解析的时候,Templete里请设定Image的width,height.
     * @param uri
     */
    @Override  
    public ImageResource getImageResource(String uri) {
        ImageResource ir;  
        uri = resolveURI(uri);  
        ir = (ImageResource) imageCache.get(uri);  
        if (ir == null) {  
            try {
                ir = new ImageResource(uri, new ITextFSImage(Image.getInstance(new URL(uri))));  
            } catch (Exception e) {  
                e.printStackTrace();  
            }  
            imageCache.put(uri, ir);  
        }  
        if (ir == null) ir = new ImageResource(uri, null);  
        return ir;  
    }  
} 